﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using log4net;
using log4net.Config;

namespace NRadioTray.App
{
    static class Program
    {
        /// <summary>
        /// Application mutex field.
        /// </summary>
        private static Mutex appMutex;

        private static ILog logger;
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            log4net.Config.XmlConfigurator.Configure();
            logger = LogManager.GetLogger(typeof(Program));
            logger.Debug("Application start");
#if !DEBUG            
            bool createdNew = false;
            appMutex = new Mutex(false, "Local\\NRadioTray{69784c21-0370-43d6-ab65-a1a5710432d4}", out createdNew);

            if (!createdNew)
            {
                logger.Error("NRadioTray is already running.");
                MessageBox.Show("NRadioTray is already running.", "NRadioTray", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
#endif            
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainView(logger));
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            logger.ErrorFormat("Unexpected error: {0}", e.ExceptionObject);

            MessageBox.Show("Unexpected error", "NRadioTray");
            logger.Debug("Application exit");
            Application.Exit();
        }
    }
}
